package com.mobile.struts.action.grid;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mobile.gridUtil.FilterBean;
import com.mobile.gridUtil.ParseFilterData;
import com.mobile.struts.action.BaseDispatchAction;
import com.mobile.tools.BeanUtil;
import com.mobile.tools.JsonHelp;
import com.mobile.tools.POIExcel;
import com.mobile.tools.PageBean;

public abstract class GridAction<T> extends BaseDispatchAction {
	protected JsonHelp<T> jsonHelp=new JsonHelp<T>();

	/**
	 * 获得GridActionUtil类
	 * @return
	 */
	protected abstract GridActionUtil<T> getGridActionUtil(HttpServletRequest request);
	
	/**
	 * 显示grid页面
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute("title",getGridActionUtil(request).getTitle());
		request.setAttribute("jsSrc",getGridActionUtil(request).getJsSrc());
		return mapping.findForward("show");
	}
	/**
	 * 通过ajax在后台读取数据
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward ajaxList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		Map<String,FilterBean> map=createFilterMap(request);		
		String deptId="deptId";
		String userId="userId";
		/*templeteManageForm.setDeptId(deptId);
		templeteManageForm.setUserId(userId);*/
		
		String startStr=request.getParameter("start");
		String limit=request.getParameter("limit");
		
		int start=0;
		int pageSize=10;
		if(startStr!=null&&!startStr.equals("0")&&limit!=null){
			pageSize=Integer.valueOf(limit);
			int temp=Integer.valueOf(startStr)/pageSize;
			start=temp+1;
		}
		PrintWriter out=null;
		
		try {
			PageBean<T> pb=getGridActionUtil(request)
								.getPib()
								.getPageBean(start,pageSize,map);
			
			
			out=response.getWriter();
			StringBuffer content=new StringBuffer();
			content.append("{'results':"+pb.getTotalSize()+",");
			content.append("'rows':"+
					jsonHelp
						.getJson(pb
								.getList(), 
								getGridActionUtil(request)
													.getFields())+"}");
			out.println(content);
		} catch(Exception e){
			e.printStackTrace();
		}finally{		
			out.close();
		}	
		return null;
	}
	/**
	 * 创建FilterMap用于查询
	 * @param request			请求变量
	 * @return
	 */
	public Map<String,FilterBean> createFilterMap(HttpServletRequest request){
		Enumeration enu= request.getParameterNames();
		Map<String,FilterBean> map=new HashMap<String,FilterBean>();
		/*
		 * 解析request里面的数据
		 */
		try {
			while(enu.hasMoreElements()){
				String name=(String)enu.nextElement();
				if(name.contains("filter")){
					/*
					 * 解析request中的name
					 */
					String[] array=ParseFilterData.parse(name);
					String value=request.getParameter(name);
					FilterBean filterBean=null;
					/*
					 * map中的键 
					 */
					String key=array[0];
					/*
					 * 如果map中有key键则读取出键值，如果没有则创建一个
					 */
					if(map.containsKey(key)){
						filterBean=map.get(key);
						PropertyDescriptor pd=new PropertyDescriptor(array[1],filterBean.getClass());
						pd.getWriteMethod().invoke(filterBean,value );
					}else{
						filterBean=new FilterBean();
						PropertyDescriptor pd=new PropertyDescriptor(array[1],filterBean.getClass());
						pd.getWriteMethod().invoke(filterBean,value );
						map.put(key, filterBean);
					}
				}
			}
		} catch (IntrospectionException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e){
			e.printStackTrace();
		} catch (InvocationTargetException e){
			e.printStackTrace();
		}
		
		return map;
	}
	
	/**
	 * 通过ajax发送要删除的数据的id到后台
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward ajaxDelete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		String uniqueCodes=request.getParameter("uniqueCodes");
		String[] uniqueCodeArray=uniqueCodes.split(",");
		
		try{
			getGridActionUtil(request)
			.getPib()
			.delete(uniqueCodeArray);
		}catch (RuntimeException e){
			e.printStackTrace();
			PrintWriter out=null;
			try {
				out=response.getWriter();
				StringBuffer content=new StringBuffer();
				content.append("({errors:'删除失败请联系管理员！'})");
				out.print(content);
			} catch(Exception ex){
				ex.printStackTrace();
			}finally{		
				out.close();
			}	
		}
		return null;
	}
	/**
	 * 显示要编辑的数据
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward ajaxEdit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {		
		String uniqueCode=request.getParameter("uniqueCode");

		T pojo=getGridActionUtil(request).getPib().findById(getGridActionUtil(request).getPojo().getClass(),uniqueCode);
		
		PrintWriter out=null;
		try {
			out=response.getWriter();
			StringBuffer content=new StringBuffer();
			content.append("{success: true,");
			content.append("data:"+jsonHelp.getJson(pojo, getGridActionUtil(request).getFields())+"}");
			out.println(content);
		} catch(Exception e){
			e.printStackTrace();
		}finally{		
			out.close();
		}
		return null;
	}
	/**
	 * 发送数据到后台并保存
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return		
	 */
	public ActionForward ajaxSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String deptId="deptId";
		String userId="userId";
		Object pojoBase=getGridActionUtil(request).getPib().getPojo();
		

		try {
			
			Object pojo=pojoBase.getClass().newInstance();
			
			BeanUtils.populate(pojo, request.getParameterMap());
			if(pojoBase!=null){
				BeanUtil.copyPropertiesWithoutNull(pojo, pojoBase);
			}		
			getGridActionUtil(request).getPib().merge(pojo);
		} catch(Exception e){
			PrintWriter out=null;
			try {				
				out=response.getWriter();
				out.println(JsonHelp.getFormFailJson("保存数据失败！"));
				e.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} finally{
				out.close();
			}
		}
		return null;	
	}
	/**
	 * 到处excel表
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward export(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		POIExcel<T> poie=new POIExcel<T>();
		OutputStream os = null;
		Map<String,FilterBean> map=createFilterMap(request);
		try {
			os = response.getOutputStream();
			response.reset();
			response.setContentType("application/x-msdownload;charset=UTF-8");
			response.setHeader("content-disposition",
			     "attachment; filename=dataexport.xls");
			List<T> list=getGridActionUtil(request)
							.getPib()
							.getAllList( map);
			if(list==null){
				list=new ArrayList<T>();
			}
			poie.exportExcel(getGridActionUtil(request).getTitle(),os,list,getGridActionUtil(request).getPojo().getClass());	
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally{
			try {
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
		//return null;
		return mapping.findForward(mapping.getInput());
	}
	
}
